//
//  SequentialSpread.m
//  SujetObserver
//
//  Created by Pierre DUCHENE on 14/02/10.
//  Copyright 2010 Pierre DUCHENE. All rights reserved.
//

#import "SequentialSpread.h"
#import "ObserverProtocol.h"
#import "SensorData.h"
#import "SensorProtocol.h"

@implementation SequentialSpread

#pragma mark -
#pragma mark Memory Management
- (id) init
{
	self = [super init];
	if (self != nil) {
		updateInProgress = NO;
		copyData = nil;
	}
	return self;
}

- (void) dealloc
{
	[copyData release];
	copyData = nil;
	
	[super dealloc];
}

#pragma mark -
#pragma mark SpreadProtocol Implementation

- (void)execute
{	
	// Check if we can send a new value update
	if ([[updateQueue operations] count] == 0) { // Mean no observers have update in progress
		[copyData release];
		copyData = [[sensor dataForContext] copy];
		// Update all observers
		NSSet* observers = [sensor getAllObservers];
		NSInvocationOperation* io = nil;
		for (id<ObserverProtocol> o in observers) {
			io = [[NSInvocationOperation alloc] initWithTarget:o
													  selector:@selector(update:)
														object:sensor];
			[updateQueue addOperation:io];
			[io release];
			io = nil;
		}
	}
	else {
		// Nothing to do
		// We loose new value until all observers are notified
	}
}

- (SensorData*)sensorData
{
	return copyData;
}

@end
